<template>
  <div class="cart-container">
    <el-card class="cart-card">
      <template #header>
        <div class="cart-header">
          <h3>我的购物车</h3>
          <el-button type="primary" @click="handleCheckout" :disabled="!cartItems.length">
            结算
          </el-button>
        </div>
      </template>

      <div v-if="cartItems.length" class="cart-content">
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品信息">
            <template #default="{ row }">
              <div class="drug-info">
                <img :src="row.drug.image" class="drug-image">
                <div class="drug-details">
                  <h4>{{ row.drug.name }}</h4>
                  <p>规格：{{ row.drug.specification }}</p>
                  <p>厂家：{{ row.drug.manufacturer }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ row.drug.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="150">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.quantity" 
                :min="1" 
                :max="row.drug.stock"
                @change="(value) => handleQuantityChange(row, value)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <span class="subtotal">¥{{ (row.drug.price * row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button 
                type="danger" 
                size="small"
                @click="handleRemove(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-footer">
          <div class="cart-total">
            <span>总计：</span>
            <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <el-empty v-else description="购物车是空的" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCartItems, updateCartItem, removeFromCart } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const cartItems = ref([])

const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    return sum + item.drug.price * item.quantity
  }, 0)
})

const loadCartItems = async () => {
  try {
    if (!userStore.user?.id) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    const { data } = await getCartItems(userStore.user.id)
    cartItems.value = data
  } catch (error) {
    ElMessage.error('获取购物车失败')
  }
}

const handleQuantityChange = async (item, value) => {
  try {
    await updateCartItem(item.id, { quantity: value })
  } catch (error) {
    ElMessage.error('更新数量失败')
    loadCartItems() // 重新加载以恢复原始数据
  }
}

const handleRemove = async (item) => {
  try {
    await ElMessageBox.confirm('确定要从购物车中删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await removeFromCart(item.id)
    ElMessage.success('删除成功')
    loadCartItems()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleCheckout = () => {
  router.push('/user/checkout')
}

onMounted(() => {
  loadCartItems()
})
</script>

<style scoped>
.cart-container {
  min-height: 100%;
}

.cart-card {
  margin-bottom: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h3 {
  margin: 0;
  color: #333;
}

.drug-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.drug-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.drug-details h4 {
  margin: 0 0 8px;
  font-size: 14px;
  color: #333;
}

.drug-details p {
  margin: 4px 0;
  font-size: 12px;
  color: #666;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.cart-total {
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}
</style> 